<template>
  <div class="num-wrapper">
    <div class="sub" @click="decrement">-</div>
<!--    <div class="num">{{ item.quantity }}</div>-->
    <input type="text" class="num" v-model.number="item.quantity" @change="changeNum" />
    <div class="add" @click="increment">+</div>
  </div>
</template>

<script>
import api from '@/api'
// 添加每次数量
// const unit = 5
export default {
  name: 'CartNum',
  props: {
    item: {
      type: Object,
      default() {
        return { quantity: 1 }
      }
    }
  },
  data() {
    return {
      unit: +this.item.product.unit
    }
  },
  watch: {
    item: {
      handler(v) {
        console.log(v)
        this.unit = +v.product.unit
      },
      deep: true
    }
  },
  methods: {
    changeNum() {
      if (this.item.quantity % this.unit !== 0) {
        this.$createToast({
          type: 'error',
          txt: '数量必须是' + this.unit + '的倍数',
          time: 1000
        }).show()
      }
      api.Cart.changeNum({ ...this.item }).then()
      this._showQuantity()
    },
    decrement() {
      if (+this.item.quantity > this.unit) {
        this.item.quantity = +this.item.quantity - this.unit
        this.item.selected = true
        // api delay
        api.Cart.decrement({ ...this.item, unit: this.unit }).then()
        this._showQuantity()
      }
    },
    increment() {
      console.log(this.unit)
      if (+this.item.quantity + this.unit <= +this.item.product.stock) {
        this.item.quantity = +this.item.quantity + this.unit
        this.item.selected = true
        // 延迟处理数据库
        api.Cart.increment({ ...this.item, unit: this.unit }).then()
        this._showQuantity()
      } else {
        this.$createToast({
          type: 'error',
          txt: '库存不足',
          time: 1000
        }).show()
      }
    },
    // 显示底栏数量, 这里是不科学的
    // 这是只是显示详情底栏, 单个商品的数量
    _showQuantity() {
      const path = this.$route.path
      if (path !== '/cart') {
        return setTimeout(() => {
          this.$router.push('/cart')
        }, 300)
      }
      this.$store.dispatch('ExecCart/set_change_list', [this.item]).then(() => {
        // console.log(this.$store.getters['ExecCart/showTotal'])
      })
    }
  }
}
</script>

<style scoped lang="stylus">
$size = 22px
$button = $size + 5px

.num-wrapper
  display flex
  text-align center
  .sub, .num, .add
    border 1px solid #dcdcdc
    min-width $size
    height $size
    line-height $size
  .sub, .add
    min-width $button
    font-weight 700
  .sub
    border-right none
    border-top-left-radius 10px
    border-bottom-left-radius 10px
  .add
    border-left none
    border-top-right-radius 10px
    border-bottom-right-radius 10px
  .num
    width 40px
    text-align center
</style>
